package edu.yourl.presenter;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import edu.yourl.domain.Domain;
import edu.yourl.domain.Gossip;
import edu.yourl.domain.Gossiper;
import edu.yourl.domain.Url;
import edu.yourl.domain.User;
import edu.yourl.persistence.IFavoritableRepository;
import edu.yourl.web.IGossiperPage;

public class GossiperPagePresenter extends BasePagePresenter implements IGossiperPagePresenter {

	private IFavoritableRepository favoritableRepository;

	private Gossiper getGossiper(IGossiperPage page) {
		return favoritableRepository.findFavoritableBySeoFriendlyId(page.getGossiperType(), page.getGossiperSEOId());
	}
	
	@Override
	@Transactional
	public void addToFavorites(IGossiperPage page) {
		User user = getCurrentUser(page);
		Gossiper gossiper = getGossiper(page);
		user.addFavorite(gossiper);
		this.userRepository.add(user);
	}

	@Override
	public List<Gossip> getList(IGossiperPage page) {
		Gossiper gossiper = getGossiper(page);
		return gossiper.getGossips();
	}

	@Override
	public String getName(IGossiperPage page) {
		Gossiper gossiper = getGossiper(page);
		return gossiper.getFavoritableName();
	}

	@Override
	public boolean isFavoriteActionVisible(IGossiperPage page) {
		User user = getCurrentUser(page);
		Gossiper gossiper = getGossiper(page);
		return !user.getFavorites().contains(gossiper);
	}

	public void setFavoritableRepository(
			IFavoritableRepository favoritableRepository) {
		this.favoritableRepository = favoritableRepository;
	}

	@Override
	public void init(IGossiperPage page) {
		Gossiper gossiper = getGossiper(page);
		String followLink = null;
		boolean iam = false;
		if (gossiper instanceof User ) {
			iam = User.class.cast(gossiper).getNickname().equals(page.getCurrentUserNick());
		} else if (gossiper instanceof Url) {
			followLink = Url.class.cast(gossiper).getUrl();
		} else {
			followLink = Domain.class.cast(gossiper).getFavoritableName();
		}
		page.setMyPage(iam);
		page.setFollowLink(followLink);
	}


}
